// Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
package main

import (
	"fmt"
	"os"

	"codehub-g.huawei.com/videocloud/mediaprocesscenter/application-gateway/pkg/redisserver"

	"github.com/beego/beego/v2/server/web"

	"codehub-g.huawei.com/videocloud/mediaprocesscenter/application-gateway/config"
	"codehub-g.huawei.com/videocloud/mediaprocesscenter/application-gateway/pkg/controllers"
	"codehub-g.huawei.com/videocloud/mediaprocesscenter/application-gateway/pkg/distributedlock"
	"codehub-g.huawei.com/videocloud/mediaprocesscenter/application-gateway/pkg/filters"
	"codehub-g.huawei.com/videocloud/mediaprocesscenter/application-gateway/pkg/metrics"
	"codehub-g.huawei.com/videocloud/mediaprocesscenter/application-gateway/pkg/models"
	"codehub-g.huawei.com/videocloud/mediaprocesscenter/application-gateway/pkg/routers"
	"codehub-g.huawei.com/videocloud/mediaprocesscenter/application-gateway/pkg/task"
	"codehub-g.huawei.com/videocloud/mediaprocesscenter/application-gateway/pkg/utils/clean"
	"codehub-g.huawei.com/videocloud/mediaprocesscenter/application-gateway/pkg/utils/clients"
	"codehub-g.huawei.com/videocloud/mediaprocesscenter/application-gateway/pkg/utils/hhmac"
	"codehub-g.huawei.com/videocloud/mediaprocesscenter/application-gateway/pkg/utils/log"
	"codehub-g.huawei.com/videocloud/mediaprocesscenter/application-gateway/pkg/utils/validator"
)

// ReturnErr return when err is not nil
func ReturnErr(err error) {
	if err != nil {
		fmt.Printf("app gateway init failed for %v\n", err)
		os.Exit(1)
	}
}

func InitDistributedlock(stopCh <-chan struct{}){
	// 实例任务
	task.InitInstanceTask(stopCh)
	// 监控任务
	task.InitMonitorTask(stopCh)
	// 接管任务
	task.InitTakeoverTask(stopCh)
	// init metrics
	metrics.Init(stopCh)
	// 启动server session dispatcher
	task.InitServerSessionDispatch(stopCh)

	// 备份app process任务
	task.InitAppProcessBackupTask(stopCh)
	// 备份server session任务
	task.InitServerSessionBackupTask(stopCh)
	// 备份client session任务
	task.InitClientSessionBackupTask(stopCh)
}


func main() {

	ReturnErr(config.Init())
	ReturnErr(log.InitLog())
	ReturnErr(models.InitDB())
	ReturnErr(redisserver.Init())
	ReturnErr(validator.Init())
	ReturnErr(hhmac.InitHMACKey())
	
	// 初始化退出信号
	stopCh := distributedlock.SetupSignalHandler()
	InitDistributedlock(stopCh)

	clients.InitAASSClient() // default timeout seconds

	// init beego web
	// set this so that we can get request body
	web.BConfig.CopyRequestBody = true

	controllers.Init()
	filters.InitFilters()
	routers.InitRouters()

	clean.Init()
	web.Run(config.GlobalConfig.GatewayAddr)
}
